import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from './components/Login.vue'
import Home from './components/Home.vue'
import Welcome from './components/Welcome.vue'
import GoodsList from './components/goods/List.vue'
import GoodAdd from './components/goods/Add.vue'
import OrderList from './components/order/List.vue'
import Settings from './components/setting/Settings.vue'
import Decorate from './components/setting/Decorate.vue'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    {
      path: '/home',
      component: Home,
      redirect: '/welcome',
      children: [
        { path: '/welcome', component: Welcome },
        { path: '/settings', component: Settings },
        { path: '/setting/decorate', component: Decorate },
        { path: '/orders', component: OrderList },
        { path: '/goods', component: GoodsList },
        { path: '/goods/add', component: GoodAdd }
      ]
    }
  ]
})

// 挂载路由导航守卫：to表示将要访问的路径，from表示从哪里来，next是下一个要做的操作 next('/login')强制跳转login
// 此功能主要用来做鉴权处理
router.beforeEach((to, from, next) => {
  // 访问登录页，放行
  if (to.path === '/login') return next()
  // 获取token
  const tokenStr = window.sessionStorage.getItem('token')
  // 没有token, 强制跳转到登录页
  if (!tokenStr) return next('/login')
  next()
})

export default router
